import { all, call, put, select, takeLatest } from 'redux-saga/effects'
import { CREATE_SHIP_ADDRESS, DELETE_SHIP_ADDRESS, GET_SHIP_ADDRESS, UPDATE_SHIP_ADDRESS } from '@ACTIONS/address'
import {
  AddressActionITF,
  AddressCreateActionITF,
  AddressDeleteActionITF,
  AddressUpdateActionITF
} from '@REDUXITF/address'
import { getShipAddressData } from '@SAGAS/dataSelect'
import api from '@API'
import { DEFAULT_TAKE } from '@CONSTANTS/common'
import Navigate from '@NAVIGATION/navigateManager'

const getShipAddress = function* getShipAddress(action: AddressActionITF) {
  try {
    const { isInit, isSetDefaultAddress } = action
    const list = yield select(getShipAddressData)
    const realSkip = isInit ? 0 : list.length
    const data = yield call(api.getMyAddresses, {
      take: DEFAULT_TAKE,
      skip: realSkip,
    })
    yield put({
      type: GET_SHIP_ADDRESS.SUCCESS,
      data,
      canLoadMore: data.length >= DEFAULT_TAKE,
      isInit,
      isSetDefaultAddress
    })
  } catch (error) {
    yield put({ type: GET_SHIP_ADDRESS.FAILURE, error })
  }
}

const deleteShipAddress = function* deleteShipAddress(action: AddressDeleteActionITF) {
  try {
    const { p8Id } = action
    yield call(api.archiveAddress, { AddressId: p8Id })
    yield put({
      type: DELETE_SHIP_ADDRESS.SUCCESS, p8Id
    })
    Navigate.navigateBack()
  } catch (error) {
    yield put({ type: DELETE_SHIP_ADDRESS.FAILURE, error })
  }
}

const createShipAddress = function* createShipAddress(action: AddressCreateActionITF) {
  try {
    const { address, isSelected } = action
    const data = yield call(api.createMyAddress, address)
    yield put({
      type: CREATE_SHIP_ADDRESS.SUCCESS,
      address: data,
      isSelected
    })
    Navigate.navigateBack()
  } catch (error) {
    yield put({ type: CREATE_SHIP_ADDRESS.FAILURE, error })
  }
}
const updateShipAddress = function* updateShipAddress(action: AddressUpdateActionITF) {
  try {
    const { address } = action
    const data = yield call(api.updateMyAddress, address)
    yield put({
      type: UPDATE_SHIP_ADDRESS.SUCCESS,
      address: data,
    })
    Navigate.navigateBack()
  } catch (error) {
    yield put({ type: UPDATE_SHIP_ADDRESS.FAILURE, error })
  }
}
export default function* rootSaga(): Generator {
  yield all([
    takeLatest(GET_SHIP_ADDRESS.REQUEST, getShipAddress),
    takeLatest(DELETE_SHIP_ADDRESS.REQUEST, deleteShipAddress),
    takeLatest(CREATE_SHIP_ADDRESS.REQUEST, createShipAddress),
    takeLatest(UPDATE_SHIP_ADDRESS.REQUEST, updateShipAddress),
  ])
}
